﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Security.Cryptography;
using CommModule.Security;

namespace CommModule.Messages
{
    public class CertSKExchangeMessage: Convertible
    {
        private int _clientChallenge;
        private String _sessionKey;
        private String _cipheredSKMessage;

        public CertSKExchangeMessage() { }

        public byte[] GetSessionKey()
        {
            RSACryptoServiceProvider decryptor = CertificateUtils.GetServerPrivateKey();
            String serializedMessage = AssimEncryption.Decrypt(_cipheredSKMessage, decryptor);

            CertSKExchangeMessage skMessage = (CertSKExchangeMessage)ObjectSerialization.DeserializeObjectFromXml(Encoding.UTF8.GetBytes(serializedMessage));
            _clientChallenge = skMessage._clientChallenge;
            _sessionKey = skMessage._sessionKey;

            return Convert.FromBase64String(_sessionKey);
        }

        public int GetClientChallenge()
        {
            return _clientChallenge;
        }

        public void ConvertToCanonic(XmlWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("CertSKExchangeMessage");

            if (_clientChallenge != null)
            {
                xmlWriter.WriteStartElement("ClientChallenge");
                xmlWriter.WriteString(_clientChallenge.ToString());
                xmlWriter.WriteEndElement();
            }

            if (_sessionKey != null)
            {
                xmlWriter.WriteStartElement("SessionKey");
                xmlWriter.WriteString(_sessionKey);
                xmlWriter.WriteEndElement();
            }

            if (_cipheredSKMessage != null)
            {
                xmlWriter.WriteStartElement("CipheredSKMessage");
                xmlWriter.WriteString(_cipheredSKMessage);
                xmlWriter.WriteEndElement();
            }

            xmlWriter.WriteEndElement();
        }

        public void ConvertFromCanonic(XmlTextReader xmlTextReader)
        {
            xmlTextReader.ReadStartElement();

            if (xmlTextReader.Name == "ClientChallenge")
            {
                _clientChallenge = xmlTextReader.ReadElementContentAsInt();
            }

            if (xmlTextReader.Name == "SessionKey")
            {
                _sessionKey = xmlTextReader.ReadElementContentAsString();
            }

            if (xmlTextReader.Name == "CipheredSKMessage")
            {
                _cipheredSKMessage = xmlTextReader.ReadElementContentAsString();
            }

            xmlTextReader.ReadEndElement();
        }

    }
}
